<template>
	<el-dialog v-model="visible" :title="!dataForm.id ? $t('add') : $t('edit')" :close-on-click-modal="false" width="800px" :destroy-on-close="true" top="5vh">
		<el-form ref="dataFormRef" :model="dataForm" :rules="dataRules" label-width="120px">
			<el-form-item prop="type_name" :label="$t('cm.p7')" class="org-list">
				<el-popover ref="typeListPopover" placement="bottom-start" trigger="click" :width="400" popper-class="popover-pop">
					<template #reference>
						<el-input v-model="dataForm.type_name" :readonly="true" :placeholder="$t('PleaseSelect')">
							<!-- <template #suffix>
								<svg-icon v-if="dataForm.type_id !== '0'" icon="icon-close-circle" @click.stop="typeSetDefaultHandle()"></svg-icon>
							</template> -->
						</el-input>
					</template>
					<div class="popover-pop-body">
						<el-tree
							ref="typeListTree"
							:data="typeList"
							:props="{ label: 'name', children: 'children' }"
							node-key="id"
							:default-expand-all="true"
							:highlight-current="true"
							:expand-on-click-node="false"
							accordion
							@current-change="typeCurrentChange"
						>
						</el-tree>
					</div>
				</el-popover>
			</el-form-item>
            <!-- <el-form-item prop="sort" label="产品规格">
				<div class="w100">
                    <el-scrollbar max-height="170px" always>
                        <div class="w100 flex flexL mb10" v-for="(item,index) in specOptions" :key="item.id">
                            <div class="flex1">
                                <el-select v-model="item.spec_id" placeholder="请输入选择规格" filterable style="width: 100%;">
                                    <el-option v-for="i in specAttrList" :key="i.value" :label="i.label" :value="i.value" />
                                </el-select>
                            </div>
                            <div class="flex1 ml10 mr10">
                                <el-input v-model="item.spec_value" placeholder="请输入规格值"></el-input>
                            </div>
                            <div class="flexl flexL mr10">
                                <el-icon @click="addspec()" v-if="index == 0" class="pointer" :size="24"><CirclePlusFilled /></el-icon>
							    <el-icon @click="delspec(index)" v-else class="pointer" :size="24"><RemoveFilled /></el-icon>
                            </div>
                        </div>
                    </el-scrollbar>
                </div>
			</el-form-item> -->
			<el-form-item prop="name" :label="$t('cm.p5')">
				<el-input v-model="dataForm.name" :placeholder="$t('cm.p5')" maxlength="140"></el-input>
			</el-form-item>
			<el-form-item prop="itemno" :label="$t('cm.p6')">
				<el-input v-model="dataForm.itemno" :placeholder="$t('cm.p6')" maxlength="140"></el-input>
			</el-form-item>
			<el-form-item prop="images" :label="$t('cm.p13')">
				<div class="w100">
                    <AUploadMultiple v-model="dataForm.images" drag multiple :limit="20" />
                </div>
			</el-form-item>
			<el-form-item prop="cost_price" :label="$t('cm.p8')">
				<el-input v-model="dataForm.cost_price" :placeholder="$t('cm.p8')" type="number"></el-input>
			</el-form-item>
			<!-- <el-form-item prop="make_price" label="成本价格">
				<el-input v-model="dataForm.make_price" placeholder="成本价格" type="number"></el-input>
			</el-form-item> -->
			<el-form-item prop="contents" :label="$t('cm.p9')">
				<el-input type="textarea" rows="5" v-model="dataForm.contents" :placeholder="$t('cm.p9')" maxlength="2550"></el-input>
			</el-form-item>
			<el-form-item prop="remark" :label="$t('cm.p10')">
				<el-input v-model="dataForm.remark" :placeholder="$t('cm.p10')" maxlength="140"></el-input>
			</el-form-item>
		</el-form>
		<template #footer>
			<el-button @click="visible = false">{{ $t('cancel') }}</el-button>
			<el-button type="primary" @click="submitHandle()">{{ $t('confirm') }}</el-button>
		</template>
	</el-dialog>
</template>

<script setup lang="ts">
import { reactive, ref, onMounted, nextTick } from 'vue'
import { Plus, Minus, CirclePlusFilled, RemoveFilled } from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus/es'
import { addProduct, getProduct, useProductTypeListApi, useProductAttrListApi, delProductSku, getSystemConfig, useProductSpecListApi } from '@/api/api'
import AUploadMultiple from "@/components/AUploadMultiple.vue";
import AUploadSingle from "@/components/AUploadSingle.vue";
import { timeResetDate } from '@/utils/tool';
import { Storage } from '@/utils/storage';
import { elMsg } from '@/utils/message';
import { useI18n } from 'vue-i18n'
const { t } = useI18n()


const emit = defineEmits(['refreshDataList'])

const visible = ref(false)
const dataFormRef = ref()
const typeList = ref([])
const attrList = ref([])
const typeListTree = ref()
const typeListPopover = ref()
const attrListTreeList = ref([])
const diyAttrList: any = ref([])
const attrListPopoverList = ref([])
const openTreeId = ref([])
const specAttrList: any = ref([])
const specOptions: any = ref([
    {
        spec_id: '',
        spec_value: '',   
    }
])
const dataForm = reactive({
	id: '',
	name: '',
	itemno: '',
	type_id: '',
	type_name: '',
	type_name_fill: '',
	images: [],
	remark: '',
	cost_price: '',
	make_price: '',
	contents: '',
})
const options: any = ref([
    {
        name: '',
        attr_id: '',
        attr_name: '',
        attr_name_fill: '',
        diy_attr: '',
        images: '',
        sort: 0,
    }
])
const addspec = () => {
	specOptions.value.push(
        {
            spec_id: '',
            spec_value: '',   
        }
    )
}
const delspec = (i) => {
	specOptions.value.splice(i,1)
}
const add = () => {
	options.value.push(
        {
            name: '',
            attr_id: '',
            attr_name: '',
            attr_name_fill: '',
            diy_attr: '',
            images: '',
            sort: 0,
        }
    )
}
const del = (i) => {
    if (dataForm.id && options.value[i].id) {
        ElMessageBox.confirm('删除后当前产品属性对应的库存信息都将同步删除，是否确定删除?', '删除产品属性', {
			confirmButtonText: '确定',
			cancelButtonText: '取消',
			type: 'error'
		})
			.then(() => {
				delProductSku(options.value[i].id).then((result) => {
                    elMsg('删除成功', 'success');
                    options.value.splice(i,1);
                }).catch((err) => {
                    
                });
			})
			.catch(() => {})
    } else {
        options.value.splice(i,1)
    }
}

const init = (id?: number) => {
	visible.value = true
	dataForm.id = ''
	dataForm.name = ''
	dataForm.itemno = ''
	dataForm.type_id = ''
	dataForm.type_name = ''
	dataForm.type_name_fill = ''
	dataForm.images = []
	dataForm.remark = ''
	dataForm.cost_price = ''
	dataForm.make_price = ''
	dataForm.contents = ''
    options.value = [
        {
            name: '',
            attr_id: '',
            attr_name: '',
            attr_name_fill: '',
            diy_attr: '',
            images: '',
            sort: 0,
        }
    ]
    specOptions.value = [
        {
            spec_id: '',
            spec_value: '',   
        }
    ]
	// 重置表单数据
	if (dataFormRef.value) {
		dataFormRef.value.resetFields()
	}

	// id 存在则为修改
	if (id) {
        dataForm.id = id;
		getDetail(id)
	} else {
        nextTick(() => {
            typeListTree.value.setCurrentKey('');
            // attrListTree.value.setCurrentKey('');
        })
    }
}
const typeCurrentChange = (data: any) => {
    console.log(data);
	dataForm.type_id = data.id
	dataForm.type_name = data.name
    if (data.two_name) {
        dataForm.type_name_fill = data.one_name+'-'+data.two_name;
    } else {
        dataForm.type_name_fill = data.one_name;
    }
    console.log('dataForm.type_name_fill', dataForm.type_name_fill);
	typeListPopover.value.hide()
}
const attrCurrentChange = (data: any, index: any) => {
    console.log(data);
	options.value[index].attr_id = data.id
	options.value[index].attr_name = data.name
	options.value[index].diy_attr = data.diy_attr
    if (data.two_name) {
        options.value[index].attr_name_fill = data.one_name+'-'+data.two_name;
    } else {
        options.value[index].attr_name_fill = data.one_name;
    }
    console.log('options.value[index].attr_name_fill', options.value[index].attr_name_fill);
	attrListPopoverList.value[index].hide()
}
// 类型设置默认值
const typeSetDefaultHandle = () => {
	dataForm.type_id = ''
	dataForm.type_name = ''
	dataForm.type_name_fill = ''
}
// 属性设置默认值
const attrSetDefaultHandle = () => {
	dataForm.attr_id = ''
	dataForm.attr_name = ''
	dataForm.attr_name_fill = ''
}
// 获取信息
const getDetail = (id: number) => {
	getProduct(id).then((res: any) => {
        const spec_contents = res.data.spec_contents;
        if (spec_contents) {
            specOptions.value = JSON.parse(spec_contents);
        }else{
            specOptions.value = [
                {
                    spec_id: '',
                    spec_value: '',   
                }
            ]
        }
        if (res.data.images&&res.data.images!='[]') {
            res.data.images = res.data.images.split(',');
        } else {
            res.data.images = [];
        }
        delete res.data.created_at;
        delete res.data.updated_at;
        delete res.data.deleted_at;
        dataForm.id = res.data.id;
        dataForm.name = res.data.name;
        dataForm.itemno = res.data.itemno;
        dataForm.type_id = res.data.type_id;
        dataForm.type_name = res.data.type_name;
        dataForm.type_name_fill = res.data.type_name_fill;
        dataForm.images = res.data.images;
        dataForm.remark = res.data.remark;
        dataForm.cost_price = res.data.cost_price;
        dataForm.make_price = res.data.make_price;
        dataForm.contents = res.data.contents;
		// Object.assign(dataForm, res.data);
        const contents = [];
        if(res.data.sku?.length){
            res.data.sku.forEach(item => {
                contents.push({
                    id: item.id,
                    attr_id: item.attr_id,
                    attr_name: item.attr_name,
                    attr_name_fill: item.attr_name_fill,
                    images: item.images,
                    sort: item.sort,
                })
            })
            options.value = contents;
        }
        nextTick(() => {
            typeListTree.value.setCurrentKey(dataForm.type_id)
            // attrListTree.value.setCurrentKey(dataForm.attr_id)
            // options.value.forEach((item,i) => {
            //     attrListTreeList.value[i].setCurrentKey(item.attr_id)
            // })
        })
	})
}
const getProductTypeList = () => {
    useProductTypeListApi().then((res: any) => {
		typeList.value = res.data;
	})
}
const getProductAttrList = () => {
    useProductAttrListApi().then((res: any) => {
        res.data.forEach(item => {
            if (item.children?.length){
                openTreeId.value.push(String(item.id));
                item.children.forEach(jtem => {
                    if (jtem.children?.length){
                        openTreeId.value.push(String(String));
                    }
                })
            }
        })
        console.log(openTreeId.value);
		attrList.value = res.data;
	})
}
const getDiyAttr = () => {
    getSystemConfig('diyattr').then((res) => {
        if (res.data.value) {
            diyAttrList.value = JSON.parse(res.data.value);
        }
    }).catch((err) => {
        
    });
}
const showDiyAttr = (value) => {
    let showValue = [];
    if (value) {
        const val = JSON.parse(value);
        val.forEach(item => {
            const attritem = diyAttrList.value.find(i => i.value==item.attr_id);
            if (attritem) {
                showValue.push(attritem.label+'：'+item.attr_value)
            }
        })
    }
    return showValue.join('\r\n');
}
const getSpec = () => {
    useProductSpecListApi().then((res) => {
        if(res.data.length){
            specAttrList.value = res.data.map(item => {
                return {
                    value: item.id,
                    label: item.name
                }
            })
        }
    }).catch((err) => {
        
    });
}
onMounted(() => {
    getProductTypeList();
    getProductAttrList();
    // getDiyAttr();
    getSpec();
})

const dataRules = ref({
	name: [{ required: true, message: t('required'), trigger: 'blur' }],
	type_name: [{ required: true, message: t('required'), trigger: 'change' }],
	// attr_name: [{ required: true, message: t('required'), trigger: 'change' }],
})

// 表单提交
const submitHandle = () => {
	dataFormRef.value.validate().then(() => {
        const params:any = JSON.parse(JSON.stringify(dataForm));
        const userinfo = Storage.getItem('user_info');
        params.operator = userinfo.strator_nickname;
        params.operator_id = userinfo.id;
        if (dataForm.id) {
            params.id = dataForm.id;
            params.updated_at = timeResetDate();
        } else {
            delete params.id;
        }
        if(params.images?.length){
            params.images = params.images.join(',');
        } else {
            delete params.images;
        }
        // const addList = specOptions.value.filter(i => i.spec_id);
        // if(addList.length){
        //     params.spec_contents = JSON.stringify(addList);
        // }
        console.log(params, options.value);
        addProduct(params).then((result) => {
            if (result) {
                ElMessage.success({
                    message: t('opaSuccess'),
                    duration: 500,
                    onClose: () => {
                        visible.value = false
                        emit('refreshDataList')
                    }
                })
            }
        }).catch((err) => {
            console.log(err);
        });
    })
}

defineExpose({
	init
})
</script>
